/**
 * 异步获取数据get/post
 * @param {string} url 接口地址
 * @param {object} data 参数
 * @param {string} type 接口请求类型 get post 非必传 默认get请求
 */

export const async = (url = '', data = {}, type = 'GET') => {
    type = type.toUpperCase()
    let timeOut = 5000 //设置超时，默认时间为5秒
    if (type == 'GET') {
        let dataStr = '' //数据拼接字符串
        Object.keys(data).forEach(key => {
            if (typeof data[key] === 'object') {
                dataStr += key + '=' + JSON.stringify(data[key]) + '&'
            } else {
                dataStr += key + '=' + data[key] + '&'
            }
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
            url = url + '?' + dataStr
        }
    }

    return new Promise((resolve, reject) => {
        let requestObj
        if (window.XMLHttpRequest) {
            requestObj = new XMLHttpRequest()
        } else {
            requestObj = new ActiveXObject()
        }

        let sendData = ''
        if (type == 'POST') {
            sendData = JSON.stringify(data)
        }

        requestObj.open(type, url, true)
        requestObj.withCredentials = true //支持跨域发送cookies
        // console.log(requestObj)
        // requestObj.setRequestHeader("Content-type", "application/json;charset=UTF-8");

        requestObj.send(sendData)

        requestObj.onreadystatechange = () => {
            if (requestObj.readyState == 4) {
                // 五秒内返回数据清除定时器·
                clearTimeout(timeOutAction)
                if (requestObj.status == 200) {
                    let obj = requestObj.response
                    if (typeof obj !== 'object') {
                        obj = JSON.parse(obj)
                    }
                    resolve(obj)
                } else {
                    reject(requestObj)
                }
            }
        }
        // 五秒超时处理
        let timeOutAction = setTimeout(() => {
            requestObj.close()
            reject('timeOut')
        }, 5000)
    })
}

/**
 * 添加JsonpApi  jsonp请求
 * @param {String} urlPath 请求路径
 * @param {object} data 网关所有参数
 * @param {object} options 其它参数,可选
 */

export const jsonpApi = (urlPath, data, options) => {
    //线上地址的pathname;
    // let adomin = `${document.location.protocol}//${process.env.serverDomain}${urlPath}?`;
    let adomin = urlPath + '?'
    options = options || {}
    options.callback = options.callback || 'callback'
    options.timeout = options.timeout || 5000
    let callbackName = options.callbackName || `jsonp_${Date.now()}_${Math.ceil(Math.random() * 100000)}`

    data[options.callback] = callbackName

    let param = ''
    for (let [key, value] of Object.entries(data)) {
        if (typeof value == 'object') {
            value = JSON.stringify(value)
        }
        param += key + '=' + value + '&'
    }
    let url = adomin + param.substring(0, param.length - 1)

    return new Promise((resolve, reject) => {
        let docHead = document.getElementsByTagName('head')[0]
        let docScript = document.createElement('script')
        docHead.appendChild(docScript)

        //发送请求
        docScript.setAttribute('src', url)

        //创建jsonp回调函数
        window[callbackName] = response => {
            docHead.removeChild(docScript)
            clearTimeout(docScript.timer)
            window[callbackName] = null
            resolve(response)
        }

        docScript.timer = setTimeout(() => {
            docHead.removeChild(docScript)
            window[callbackName] = null
            reject(new Error(`JSONP request to ${url} timed out`))
        }, options.timeout)
    })
}
